<?php

namespace Budget\BudgetBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
use Budget\BudgetBundle\Entity\Family;
use Budget\BudgetBundle\Entity\Category;

class CategoryType extends AbstractType
{
    
    protected $userFamily;
    protected $category;
    
    public function __construct(Family $userFamily, Category $category = null)
    {
        $this->userFamily = $userFamily;
        $this->category   = $category;
    }
    
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $userFamily      = $this->userFamily;
        $category        = $this->category;
        $labelSubmitName = 'Add Category';
        if ($this->category) { 
            $labelSubmitName = 'Save Category'; 
        }
        
        $builder
            ->add('name', null, array('label' => 'Category Name:'))        
            ->add('parent', 'entity', array(
                'class' => 'BudgetBudgetBundle:Category',
                'query_builder' => function(EntityRepository $er) use ($userFamily, $category) {
                    if ($category) {
                    return $er->createQueryBuilder('p')
                        ->where('p.family = :family')
                        ->andWhere('p.id != :id')
                        ->andWhere('p.date_deleted IS NULL')
                        ->setParameter('family', $userFamily->getId())
                        ->setParameter('id', $category->getId())
                        ->orderBy('p.name', 'ASC');
                    } else {
                        return $er->createQueryBuilder('p')
                        ->where('p.family = :family')
                        ->andWhere('p.date_deleted IS NULL')
                        ->setParameter('family', $userFamily->getId())
                        ->orderBy('p.name', 'ASC');
                    }
                },
                'empty_value'   => 'Main category',
                'required'      =>  false,
                'label'         => 'Category:',
                'multiple'      => false
            ))
            ->add('save', 'submit', array('label' => $labelSubmitName));
        
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'category';
    }
    
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Budget\BudgetBundle\Entity\Category',
        ));
    }

}
